package org.sample.aaatest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Service
public class TestSingle {
    @Autowired
    private TestRepo testRepo;

//    private static TestSingle testSingle;

    /**
     * 构造方法必须是public
     */
    public TestSingle() {
    }

//    @PostConstruct
//    public void init() {
//        testSingle = this;
//    }

    public static TestSingle getInstance() {
        return null;
//        return testSingle;
    }

    @CachePut(cacheNames = "testCache", key = "#user.id")
    public TestBean addUser(TestBean user) {
        log("addUser:user=" + user);
        TestBean result = testRepo.save(user);
        return result;
    }

    @CacheEvict(cacheNames = "ticketsCache", key = "#id")
    public void deleteUser(Integer id) {
        log("deleteUser:id=" + id);
        testRepo.delete(id);
    }

    @Cacheable(cacheNames = "testCache", key = "#id", unless = "#result == null")
    public TestBean getTestById(Integer id) {
        log("getTestById:id=" + id);
        TestBean one = testRepo.findOne(id);
        log("getTestById:one=" + one);
        return one;
    }

    public List<TestBean> getAll() {
        Iterable<TestBean> iterable = testRepo.findAll();
        List<TestBean> list = new ArrayList<>();
        iterable.forEach(list::add);
        log("getAll:one=" + list);
        return list;
    }

    public long count() {
        long count = testRepo.count();
        log("count:count=" + count);
        return count;
    }

    private void log(String msg) {
        System.out.println("TestSingle\t" + msg);
    }
}
